﻿
using SocketBook7Server.Script.net;
using SocketBook7Server.db;
using System;
//using SocketBook7Server.Script.proto;

namespace SocketBook7Server.Script.logic
{
    //partial 标明LoginMsgHandle类是局部类型 可以被分开写在不同的.cs文件里
    public partial class MsgHandler
    {
       //注册协议
       public static void MsgRegister(ClientState c,MsgBase msgBase)
       {
            MsgRegister msg = (MsgRegister)msgBase;
            //注册
            if (DbManager.Register(msg.id, msg.pw))
            {
                DbManager.CreatePlayer(msg.id);
                msg.result = 0;
            }
            else { msg.result = 1; }
            NetManager.Send(c, msg);
       }
        //登录
        public static void MsgLogin(ClientState c,MsgBase msgBase)
        {
            MsgLogin msg = (MsgLogin)msgBase;
            //密码校验
            if (!DbManager.CheckPassword(msg.id, msg.pw))
            {
                msg.result = 1;
                NetManager.Send(c, msg);
                return;
            }
            //不允许再次登录
            if (c.player != null)
            {
                msg.result = 1;
                NetManager.Send(c, msg);
                Console.WriteLine("已经登录了，请不要重复登录");
                return;
            }
            //如果已经登录，踢下线
            if (PlayerManager.IsOnline(msg.id))
            {
                //发送体踢下线协议
                Player other = PlayerManager.GetPlayer(msg.id);
                MsgKick msgKick = new MsgKick();
                msgKick.reson = 0;
                other.Send(msgKick);
                PlayerManager.RemovePlayer(msg.id);
                //断开连接 
                Console.WriteLine("踢下线");
                NetManager.Close(other.state);
            }
            //获取我玩家数据
            PlayerData playerData = DbManager.GetPlayerData(msg.id);
            if (playerData == null)
            {
                msg.result = 1;
                NetManager.Send(c, msg);
                return;
            }
            //构建Player
            Player player = new Player(c);
            player.id = msg.id;
            player.data = playerData;
            PlayerManager.AddPlayer(msg.id, player);
            c.player = player;
            //返回协议  
            msg.result = 0;
            player.Send(msg);
        }
        //
    }
}
